package com.bean.serializabletest.serializeutil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JacksonSerializeUtil extends AbstractSerialize{
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public <T> byte[] serialize(T obj)  {
        if (obj  == null){
            throw new NullPointerException();
        }
        byte[] bytes = null;
        try {
            bytes = mapper.writeValueAsBytes(obj);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        T obj = null;
        try {
            obj =  mapper.readValue(data, clazz);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

}
